package com.aplink.generic.xmlparser;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.text.TextUtils;

import com.aplink.generic.constant.FormDesignConstant;
import com.aplink.generic.constant.type.SharePreferenceType;
import com.aplink.generic.pojo.formdesign.Column;
import com.aplink.generic.pojo.formdesign.InitValue;

public class InitValueParser {

    public static final String DEFAULT_VALUE = "defaultValue";
    public static final String INIT_VALUE = "initValue";
    public static final String IS_TOKEN = "isToken";
    public static final String IS_USERNAME = "isUsername";
    public static final String PASSED_COLUMN_ID = "passedBy";
    private static final String SHARE_PREFERENCE_VALUE = "SharePreferenceValue";

    public static InitValue parseInitValue(Node node) {
        final InitValue initValue = new InitValue();
        Element element = (Element) node;
        NodeList nodes = element
                .getElementsByTagName(InitValueParser.INIT_VALUE);
        if (nodes.getLength() == 0) {
            return initValue;
        }
        node = nodes.item(0);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            element = (Element) node;
            nodes = element.getElementsByTagName(FormDesignConstant.COLUMN);
            for (int i = 0; i < nodes.getLength(); i++) {
                final Column column = new Column();
                final Node nodeColumn = nodes.item(i);
                if (nodeColumn.hasAttributes()) {
                    String value = XMLPaserUtil.getAttrValue(nodeColumn,
                            InitValueParser.SHARE_PREFERENCE_VALUE);
                    if (!TextUtils.isEmpty(value)) {
                        column.setPreferenceType(SharePreferenceType.get(value));
                    }

                    value = XMLPaserUtil.getAttrValue(nodeColumn,
                            InitValueParser.DEFAULT_VALUE);
                    if (!TextUtils.isEmpty(value)) {
                        column.setDefaultValue(value);
                    }

                    value = XMLPaserUtil.getAttrValue(nodeColumn,
                            InitValueParser.PASSED_COLUMN_ID);
                    if (!TextUtils.isEmpty(value)) {
                        column.setPassedColumnID(value);
                    }
                }
                final String columnValue = XMLPaserUtil
                        .getNodeValue(nodeColumn);
                column.setColumnName(columnValue);
                initValue.add(column);
            }
        }
        return initValue;
    }
}
